package admin

import (
	"github.com/gin-gonic/gin"
	"go-admin-auth/app/dal"
	"go-admin-auth/app/lib"
	"go-admin-auth/gin_helper"
	"strings"
)

type authHandler struct {
}

var (
	AuthHandler = new(authHandler)
)

type login struct {
	Username  string `json:"username" form:"username"`
	Password  string `json:"password" form:"password"`
	KeepLogin string `json:"keep_login" form:"keep_login"`
	JumpURL   string `json:"jump_url" form:"jump_url"`
}

//DefaultJumpURL 登录成功默认跳转页
var DefaultJumpURL string = "/member/userinfo_detail.html"

func (h authHandler) Index(c *gin.Context) {
	gin_helper.JsonOk(c, "welcome")
}

func (h authHandler) Login(c *gin.Context) {
	loginParams := &login{}
	err := c.ShouldBind(&loginParams)
	if nil != err {
		gin_helper.JsonErr(c, err)
	}

	adminInfo, _ := dal.UserDAO.GetByUsername(loginParams.Username)
	if nil == adminInfo {
		gin_helper.JsonFail(c, 800, "用户名或密码错误")
		return
	}

	// 密码校验
	genPwd := lib.EncryptWord(loginParams.Password, nil)
	if adminInfo.Password != genPwd {
		gin_helper.JsonFail(c, 800, "用户名或密码错误2")
		return
	}

	tokenString, err := lib.GenToken(adminInfo.Id)
	if err != nil {
		gin_helper.JsonErr(c, err)
	}

	// 设置cookie
	c.SetCookie("AdminAuthorization", tokenString, 86400, "/", c.Request.Host, false, true)

	// 如果是ajax，不需要跳转，直接输出结果
	if strings.EqualFold(c.Request.Header.Get("X-Requested-With"), "XMLHttpRequest") {
		gin_helper.JsonOk(c, gin.H{"token": tokenString, "info": gin.H{"admin_id": adminInfo.Id}, "jump_url": loginParams.JumpURL})
		return
	}
	// 登录完成跳转到jump_url
	c.Redirect(302, loginParams.JumpURL)
	return
}

func (h authHandler) Logout(c *gin.Context) {
	// 设置cookie
	c.SetCookie("AdminAuthorization", "", -1, "/", c.Request.Host, false, true)

	gin_helper.JsonOk(c, "success")
}
